# -*- coding: utf-8 -*-
"""
 @File    : rest.py
 @Time    : 2021/9/13
 @Author  : 包建强
 @Description    : restful服务
"""
import numpy as np
import tornado.httpserver
import tornado.wsgi
from flask import Flask, request
from paddleocr import PaddleOCR

import utils

app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False

@app.route('/recognition', methods=['POST'])
def ocr_reg():
    image_data = request.form.get('image_data').replace(' ', '+')

    list = []

    result = ocr.ocr(utils.base64_to_cv2(image_data), cls=True, det=True, rec=True)
    for subList in result:
        point1_x = subList[0][0][0]
        point1_y = subList[0][0][1]
        point2_x = subList[0][1][0]
        point2_y = subList[0][1][1]
        point3_x = subList[0][2][0]
        point3_y = subList[0][2][1]
        point4_x = subList[0][3][0]
        point4_y = subList[0][3][1]

        text = subList[1][0]
        accuracy = int(subList[1][1] * 100)

        entity = {
            'points': [{'x':point1_x, 'y':point1_y}, {'x':point2_x, 'y':point2_y}, {'x':point3_x, 'y':point3_y}, {'x':point4_x, 'y':point4_y}],
            'text': text,
            'accuracy': accuracy
        }

        list.append(entity)

    print(list)
    return {'paddle_result': list}


@app.route('/detect', methods=['POST'])
def ocr_detect():
    image_data = request.form.get('image_data').replace(' ', '+')

    list = []

    result = ocr.ocr(utils.base64_to_cv2(image_data), cls=True, det=True, rec=False)
    for subList in result:
        point1_x = int(subList[0][0])
        point1_y = int(subList[0][1])
        point2_x = int(subList[1][0])
        point2_y = int(subList[1][1])
        point3_x = int(subList[2][0])
        point3_y = int(subList[2][1])
        point4_x = int(subList[3][0])
        point4_y = int(subList[3][1])

        entity = {
            'points': [{'x':point1_x, 'y':point1_y}, {'x':point2_x, 'y':point2_y}, {'x':point3_x, 'y':point3_y}, {'x':point4_x, 'y':point4_y}],
        }

        list.append(entity)

    print(list)
    return {'paddle_result': list}



@app.route('/regregion', methods=['POST'])
def ocr_reg_region():
    image_data = request.form.get('image_data').replace(' ', '+')
    p1_x = int(request.form.get('p1_x'))
    p1_y = int(request.form.get('p1_y'))
    p2_x = int(request.form.get('p2_x'))
    p2_y = int(request.form.get('p2_y'))
    p3_x = int(request.form.get('p3_x'))
    p3_y = int(request.form.get('p3_y'))
    p4_x = int(request.form.get('p4_x'))
    p4_y = int(request.form.get('p4_y'))

    box = [[p1_x, p1_y],[p2_x, p2_y],[p3_x, p3_y],[p4_x, p4_y]]

    img_crop = utils.get_rotate_crop_image(utils.base64_to_cv2(image_data), np.array(box, np.float32))
    if img_crop is None:
        return {'error': '识别不出！'}

    result = ocr.ocr(img_crop, cls=True, det=False, rec=True)
    if result[0][0] != '':
        return {
            'text': result[0][0],
            'accuracy': int(result[0][1] * 100)
        }

    else:
        return {'error': '识别不出！'}



def start_tornado(app, port=5000):
    http_server = tornado.httpserver.HTTPServer(
        tornado.wsgi.WSGIContainer(app))
    http_server.listen(port)
    print("Tornado server starting on port {}".format(port))
    tornado.ioloop.IOLoop.instance().start()


if __name__ == '__main__':
    ocr = PaddleOCR(use_pdserving=False, use_angle_cls=True, det=True, cls=True, use_gpu=False, lang='ch')

    # 启动restful服务
    start_tornado(app, 5000)
